package com.wu.power;

/**
 * 给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
 * 保证base和exponent不同时为0
 */
public class Solution {
    public double power(double base, int exponent) {
        /*if (base == 0.0) {
            return 0.0;
        } else if (exponent == 0) {
            return 1;
        }
        double value = 1.0;

        int res = exponent > 0 ? exponent : -exponent;

        for (int i = 0; i < res; i++) {
            value = base * base;
        }
        return exponent > 0 ? value : value;*/

        if (exponent < 0) {
            base = 1 / base;
            exponent = -exponent;
        }
        return rePower(base, exponent);
    }

    private double rePower(double base, int exponent) {
        if (exponent == 0) {
            return 1.0;
        }

        double res = rePower(base, exponent >> 1);
        res *= res;
        if ((exponent % 2) == 1) {
            res *= base;
        }
        return res;
    }
}